<template>
  <div class="scheduling-system" v-loading="loading" element-loading-text="加载中。。。">
    <el-card>
      <el-alert title="周试图下不允许进行修改哦~" type="warning" v-show="view=='week'" style="margin-bottom: 20px;"></el-alert>

      <!-- 
          :select-allow="handlerSeelctAllow"
          aspectRatio="100" 
          scrollTime="00:00"
          :slotDuration='slotDuration'
      -->
      <template>
        <FullCalendar
          ref="calendar"
          locale='zh-cn'
          :defaultDate="defaultDate"
          :defaultView="defaultView" 
          :plugins="calendarPlugins" 
          :resourceLabelText="resourceLabelText"
          :resources="resources"
          :header="header"
          :resourceColumns="resourceColumns"
          :resourceAreaWidth="resourceAreaWidth"
          :views="views"
          :selectHelper="true"
          :select-mirror="true"
          :droppable="true"
          :editable="editable"
          :navLinks="false"
          :unselect-auto="true"
          :select-overlap="false"
          :slotEventOverlap="false"
          :eventOverlap="false"
          :eventStartEditable="eventStartEditable" 
          :eventDurationEditable="eventDurationEditable"
          :selectable="selectable"
          :displayEventEnd="true"
          :displayEventTime="true"
          :weekNumberTitle="weekNumberTitle"
          :buttonText="buttonText"
          :events="events"
          :dayRender="dayRender"
          @dateClick="dateClick"
          @select="select"
          @eventClick="eventClick"
          @eventDrop="eventDrop"
          @eventDragStart="eventDragStart"
          @dayClick="dayClick"
          @eventMouseover="eventMouseover"
          @eventResizeStop ="eventResizeStop"
          @eventResize="eventResize"
          @eventResizeStart="eventResizeStart"/>
      </template>
    
      <!-- 添加事件弹窗 -->
      <el-dialog
        title="添加事件"
        :visible.sync="dialogVisible"
        width="30%"
        @close="dialogVisible = false">
        <el-input v-model="input" placeholder="请输入事件名称"></el-input>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAdd">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { Calendar } from '@fullcalendar/core';
import resourceTimelinePlugin from '@fullcalendar/resource-timeline';
import FullCalendar from '@fullcalendar/vue'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlulgin from '@fullcalendar/timegrid'
import '@fullcalendar/core/locales/zh-cn' // 支持中文
import momentPlugin from '@fullcalendar/moment'
import interactionPlugin from '@fullcalendar/interaction'
import toolBox from '@/common/utils/toolBox'
// 通讯相关
import request from "@/common/utils/requestWFM";
import scheduleQuery from "@/message/wfm/userScheduleManage/scheduleReport/scheduleQuery";

export default {
  name: "scheduling-system",
  components: {
    FullCalendar,
  },
  data() {
    return {
      loading: false,
      // 随时判断时间是否合法，通过返回true/false来判断是否能够选择
      // handlerSeelctAllow: info => {
        // console.log('handlerSeelctAllow',info);
        // const currentDate = new Date()
        // const start = info.start
        // const end = info.end
        // return (start <= end && start >= currentDate)
      // },
      calendarPlugins: [resourceTimelinePlugin,momentPlugin,interactionPlugin,dayGridPlugin],
      defaultDate: new Date(),
      editable: true, 
      selectable: true,
      eventStartEditable: true,
      eventDurationEditable: true,
      // scrollTime: '09:00',
      // monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
      // monthNamesShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
      // dayNames: ["周日", "周一", "周二", "周三", "周四", "周五", "周六"],
      // dayNamesShort: ["123", "周一", "周二", "周三", "周四", "周五", "周六"],
      defaultView: "resourceTimelineDay",
      resourceLabelText: '人员安排',
      header: {
        left: 'prev,next, today',
        center: 'title',
        right: 'resourceTimelineDay,resourceTimelineWeek,'
      },
      // slotDuration: '00:15:00',
      weekNumberTitle:'1',
      // 左侧人员列表
      resources: [
        // { id: 'a', title: 'Auditorium A',money: 32.00},
        // { id: 'b', title: 'Auditorium B', eventColor: 'green', money: 32.00},
        // { id: 'c', title: 'Auditorium C', eventColor: 'orange' },
      ],
      eventsDay: [
        // url: 'baidu.com' ,
        // { id: '1', resourceId: 'b', start: '2019-09-19', end: '2019-09-19T07:00:00', title: 'event 1' ,color: 'red'},
        // { id: '1', resourceId: 'b', start: '2019-09-19T06:00', end: '2019-09-19T07:00:00', title: 'event 1' ,color: '#909090'},
        // { id: '1', resourceId: 'b', start: '2019-09-19T07:00', end: '2019-09-19T11:00:00', title: 'event 1' ,color: 'orange'},
      ],
      eventsWeek: [],
      resourceAreaWidth: '15%',
      resourceColumns: [
        // {
        //   group: true,
        //   labelText: 'Building',
        //   field: 'building'
        // },
        {
          labelText: '',
          field: 'title'
        },
        // {
        //   labelText: '',
        //   field: 'money'
        // },
        // {
        //   labelText: '',
        //   field: 'occupancy'
        // },
        // {
        //   labelText: '',
        //   field: 'white'
        // }
      ],
      views: {
        resourceTimelineDay: {
          buttonText: '日',
          slotDuration: '00:15:00',
          slotLabelFormat:"hh:mm",
        },
        resourceTimelineWeek: {
          type: 'resourceTimeline',
          slotDuration: '24:00:00',
          // duration: { days: 7 },
          buttonText: '周',
        },
        dayGridMonth: {
          buttonText: '月',
        }
      },
      buttonText: {
        today: "今天",
      },
      tags: [
        {'name':123,"id":1},
        {'name':3,"id":2},
        {'name':5,"id":3},
      ],
      dialogVisible: false,
      // 添加事件标题
      input: '',
      selectInfo: [],
      // 获取到展示日历得起始时间
      startStr:'',
      endStr:'',
      // day--日视图   week--周视图
      view: 'day',
      tableData:[],
    };
  },
  watch:{
    dialogVisible(val){
      if(!val){
        this.input = '';
      }
    }
  },
  computed:{
    events(arg) {  
      this.defaultDate = '2019-12-12';
      var date = (new Date(this.endStr).getTime()-new Date(this.startStr).getTime())/ (1000 * 60 * 60 * 24);
      if(date >= 7){
        // 周视图
        this.view = 'week';
        this.eventDurationEditable = this.eventStartEditable = this.selectable = false;
        // console.log('events',this.defaultDate);
        this.removeDom()
        return this.eventsDay ;
      }else{
        // 日式图
        this.view = 'day';
        this.eventDurationEditable = this.eventStartEditable = this.selectable = true;
        // console.log('events',this.defaultDate);
        return this.eventsWeek ;
      } 
    },
  },
  mounted() {
    this.queryModel();
    // 跳转日期
    // console.log(this.$refs.calendar.$options.calendar.gotoDate('2001-01-01'))
  },
  methods: {
    // 去掉周下面的时间
    removeDom(){
      var that = this;
      setTimeout(function(){
        let element = document.getElementsByClassName('fc-cell-text');
        for(let x=0; x<element.length; x++) {
          //  && that.slotDuration == '24:00:00'
          if(element[x].innerText == '上午12时'){
            let parent = element[x].parentNode.parentNode.parentNode.parentNode;
            let child = element[x].parentNode.parentNode.parentNode;
            parent.removeChild(child);
            break;
          }
        }
      },0);
    },
    dateClick: function(arg) {
      console.log(
        'dateClick',
        arg.date,
        arg.resource ? arg.resource.id : '(no resource)'
      );
    },
    //点击空白日期调用
    dayClick: function(date, allDay) { 
      console.log("dayClick:",date, allDay);
    },
    //点击日期控件上显示的事件触发的事件
    eventClick: function(eventObj) {
      // console.log('eventClick:'+eventObj.event.title);
      // console.log("eventClick:",eventObj)
    },
    select: function(arg) {
      this.dialogVisible = true;
      this.selectInfo = arg;
      // console.log(arg);
      // console.log(
      //   'select callback',
      //   arg.startStr,
      //   arg.endStr,
      //   arg.resource ? arg.resource.id : '(no resource)'
      // );
    },
    eventDrop: function(arg) { // called when an event (already on the calendar) is moved
      if(this.view == 'week'){
        arg.revert();
      }
      // 获取到开始、结束时间、title、转换后id  _def-> resourceIds,恢复原状
      console.log('eventDrop', arg);
      console.log('eventDrop', this.events1);
    },
    eventDragStart(arg){
      console.log('eventDragStart', arg.event);
    },
    eventMouseover(event, jsEvent, view){
      console.log("eventMouseover:",eventMouseover);
    },   
    // 确认添加事件
    submitAdd(){
      var that = this;
      this.events1.push({ 
        id: this.events1.length, 
        resourceId: that.selectInfo.resource.id,
        start: that.selectInfo.startStr, 
        end: that.selectInfo.endStr, 
        title: that.input 
      });
      console.log(this.events1);
      that.dialogVisible = false;
    },
    dayRender(info){
      // console.log('dayRender',info);
      this.startStr = info.view.activeStart;
      this.endStr = info.view.activeEnd;
    },
    eventResizeStart(arg){
      console.log('eventResizeStart',arg);
    },
    eventResizeStop(arg){
      console.log('eventResizeStop: ',arg);
    },
    // 左右选择事件更改时间调用函数，可获取到开始、结束时间
    eventResize(arg){
      console.log('eventResize',arg);
    },
    //查询字段类型
    queryModel() {
      this.loading = true;
      let resBody = new scheduleQuery();
      resBody.data.SPID = '160';
      resBody.data.QUREYSRTDATE = '20190904';
      resBody.data.QUREYENDDATE = '20200216';
      resBody.data.AGENTIDLISTSTR = '01,04';
      request(resBody)
        .then(response => {
          if (response.SYS_HEAD.ReturnCode === "000000") {
            this.tableData = response.BODY;
            this.resources = [];
            // 人员列表
            this.tableData.AGENTINFO.forEach((item,index)=>{
              this.resources.push({'id':item.AGENTID,'title':item.AGENTNAME});
            })
            // 事件列表
            // { id: '1', resourceId: 'b', start: '2019-09-19', end: '2019-09-19T07:00:00', title: 'event 1' ,color: 'red'},
            this.tableData.SCHEDULELIST.forEach((item,index)=>{
              this.eventsDay.push({
                'id':index,
                'resourceId':item.AGENTID,
                'start':item.SRTTIME,
                'end':item.ENDTIME,
                'title':item.ACTIVITYNAME,
                'color':item.CALCOLOUR,
              });
            })
          } else {
            this.$message({
              message: response.SYS_HEAD.ReturnMessage,
              type: 'error  '
            });
          }
        })
        .catch(error => {
          console.log("error", error);
        })
      this.loading = false;
    },
  }

};
</script>

<style lang='scss'>
@import '../../styles/core/main.css';
@import '../../styles/timeline/main.css';
@import '../../styles/resource-timeline/main.css';
.demo-app {
  font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
  font-size: 14px;
}
.demo-app-top {
  margin: 0 0 3em;
}
.demo-app-calendar {
  margin: 0 auto;
  max-width: 900px;
}
</style>
